//
//  APMBannerView.m
//  APMBanner
//
//  Created by apang on 2022/9/12.
//

#import "APMBannerView.h"
#import "APMBannerViewCell.h"

static NSString * const _bannerCellIdentifier = @"_bannerCell";

@interface APMBannerView()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView * collectionView;
@property (nonatomic, assign) NSInteger itemIndex;
@property (nonatomic, assign) NSInteger lastItemIndex;
@property (nonatomic, assign) NSInteger itemCount;
@property (nonatomic, assign) BOOL isFirst;

@property (nonatomic, strong) NSTimer * timer;
@end

@implementation APMBannerView

- (instancetype)init {
    if (self = [super init]) {
        [self _initial];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self _initial];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self _initial];
    }
    return self;
}

- (void)_initial {
    if (!_collectionView) {
        _isFirst = YES;
        _autoScrollDelayDuration = 1.5;
        _scrollEnable = YES;
        _autoScrollEnable = YES;
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.bounces = NO;
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.pagingEnabled = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[APMBannerViewCell class] forCellWithReuseIdentifier:_bannerCellIdentifier];
        self.collectionView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:self.collectionView];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[_collectionView]-(0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_collectionView)]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[_collectionView]-(0)-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_collectionView)]];
    }
}

// MARK: - overwrite

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.isFirst) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        if (self.autoScrollEnable && self.scrollEnable) {
            [self startTimer];
        }
    }
}

// MARK: - private

- (NSInteger)indexOfIndexPath:(NSIndexPath *)indexPath {
    NSInteger _index0 = self.itemIndex - 1 < 0 ? self.itemCount - 1 : self.itemIndex-1;
    NSInteger _index1 = self.itemIndex;
    NSInteger _index2 = self.itemIndex + 1 > self.itemCount -1 ? 0 : self.itemIndex+1;
    return indexPath.row ? (indexPath.row == 1 ? _index1 : _index2) : _index0;
}

- (void)timerHandler {
    NSInteger _index = self.scrollPosition ? 0 : 2;
    UICollectionViewScrollPosition scrollPosition = self.scrollPosition ? UICollectionViewScrollPositionRight : UICollectionViewScrollPositionLeft;
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_index inSection:0] atScrollPosition:scrollPosition animated:YES];
}

- (void)startTimer {
    [self stopTimer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.autoScrollDelayDuration target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)stopTimer {
    if (_timer && _timer.isValid) {
        [_timer invalidate];
        _timer = nil;
    }
}

//MARK: - public method

- (void)registerClass:(Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
    [self.collectionView registerClass:cellClass forCellWithReuseIdentifier:identifier];
}

- (void)registerNib:(UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier {
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:identifier];
}

- (UICollectionViewCell *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    return [self.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
}

- (void)reloadData {
    _isFirst = YES;
    self.itemIndex = 0;
    self.itemCount = 0;
    self.lastItemIndex = 0;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

- (void)setScrollEnable:(BOOL)scrollEnable {
    _scrollEnable = scrollEnable;
    if (scrollEnable) {
        if (_autoScrollEnable) {
            [self startTimer];
        }
    } else {
        [self stopTimer];
    }
    self.collectionView.scrollEnabled = scrollEnable;
}

- (void)setAutoScrollEnable:(BOOL)autoScrollEnable {
    _autoScrollEnable = autoScrollEnable;
    if (autoScrollEnable) {
        if (self.scrollEnable) {
            [self startTimer];
        }
    } else {
        [self stopTimer];
    }
}

- (void)setAutoScrollDelayDuration:(NSTimeInterval)autoScrollDelayDuration {
    _autoScrollDelayDuration = autoScrollDelayDuration;
    if (self.scrollEnable && self.autoScrollEnable) {
        [self startTimer];
    }
}

//MARK: - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return self.bounds.size;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

//MARK: - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.delegate && [self.delegate respondsToSelector:@selector(numberOfItemsInBannerView:)]) {
        self.itemCount = [self.delegate numberOfItemsInBannerView:self];
        return self.itemCount > 0 ? 3 : 0;
    }
    return 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate && [self.delegate respondsToSelector:@selector(bannerView:cellForItemAtIndexPath:itemIndex:)]) {
        NSInteger _index = [self indexOfIndexPath:indexPath];
        APMBannerViewCell * cell = [self.delegate bannerView:self cellForItemAtIndexPath:indexPath itemIndex:_index];
        return cell;
    }
    APMBannerViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:_bannerCellIdentifier forIndexPath:indexPath];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger _index = [self indexOfIndexPath:indexPath];
    if (self.delegate && [self.delegate respondsToSelector:@selector(bannerView:didSelectItemAtIndex:)]) {
        [self.delegate bannerView:self didSelectItemAtIndex:_index];
    }
}

//MARK: - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.isFirst) {
        self.isFirst = NO;
        return;
    }
    CGFloat offset = scrollView.contentOffset.x;
    if (offset <= 0) {
        if (self.itemIndex == 0) {
            self.itemIndex = self.itemCount - 1;
        } else {
            self.itemIndex -= 1;
        }
        [self.collectionView reloadData];
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    }
    if (offset >= self.collectionView.contentSize.width * (2.0/3.0)) {
        if (self.itemIndex == self.itemCount - 1) {
            self.itemIndex = 0;
        } else {
            self.itemIndex += 1;
        }
        [self.collectionView reloadData];
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:NO];
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (self.lastItemIndex == 0 || self.lastItemIndex!= self.itemIndex) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(bannerView:didShowItemAtIndex:)]) {
            [self.delegate bannerView:self didShowItemAtIndex:self.itemIndex];
        }
    }
    self.lastItemIndex = self.itemIndex;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (self.lastItemIndex == 0 || self.lastItemIndex!= self.itemIndex) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(bannerView:didShowItemAtIndex:)]) {
            [self.delegate bannerView:self didShowItemAtIndex:self.itemIndex];
        }
    }
    self.lastItemIndex = self.itemIndex;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.scrollEnable && self.autoScrollEnable) {
        [self startTimer];
    }
}
@end
